args <- commandArgs(TRUE)
setwd(args[1])
library(survival)
clin<-read.table("/data2/bsi/RandD/bora/GBM_EQTL/geneexpr_survival/clinical.txt",sep="\t",head=T,colClasses=c("character","numeric","numeric","numeric"))
rownames(clin)<-clin[,1]
data<-read.table("temp_input",sep="\t",head=T,stringsAsFactors=F)
colnames<-colnames(data)
colnames<-gsub("\\.",'-',colnames)
colnames(data)<-colnames
genelist<-data[,1]
data<-data[,as.vector(clin[,1])]
colnames_data<-colnames(data)
data<-rbind(colnames_data,data)
data<-t(data)
colnames(data)<-c("Subject",genelist)
finaldata<-merge(clin,data,by="Subject")
hazardrank<-matrix(ncol=nrow(finaldata), nrow=length(genelist))
colnames(hazardrank)<-clin[,1]
rownames(hazardrank)<-as.character(genelist)
genelist<-colnames(finaldata)
i<-5
while(i<=ncol(finaldata))
{
	print(i)
	dt1<-finaldata[,c(1:4,i)]
	colnames(dt1)<-c("Subject","TIME","EVENT","AGE","EXPR")
	dt1[,5]<-as.numeric(as.character(dt1[,5]))
	j<-1
	while(j<=20)
	{
		sub<-seq(j, nrow(dt1), by = 20)
		main<-seq(1, nrow(dt1), by = 1)
		main<-main[-sub]
		dt<-finaldata[main,c(1:4,i)]	
		colnames(dt)<-c("Subject","TIME","EVENT","AGE","EXPR")
		dt[,5]<-as.numeric(as.character(dt[,5]))
		fit<-coxph(Surv(TIME,EVENT) ~ EXPR+AGE,data=dt)
		pred <- predict(fit,dt1,type="lp")
		wanted_ranks<-rank(pred)
		hazardrank[i-4,sub]<-wanted_ranks[sub]	
		j<-j+1
	}
	i<-i+1
}
write.table(hazardrank,"hazardrank.txt",sep="\t",quote=F,col.names=T,row.names=T)
